/**
 *
 * @description:
 * @author: junyong.hong
 * @createTime: 2018/10/13
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const mongoose = require('mongoose')
const { resolve } = require('path')
// 读取多个文件
const glob = require('glob')

mongoose.Promise = global.Promise

// 初始化模型
exports.initSchemas = () => {
    glob.sync(resolve(__dirname, './schema', '**/**.js')).forEach(require)
}


exports.connect = (db) => {
    // 最大连接次数
    let maxConnectTimes = 0

    return new Promise(resolve => {
        // 本地开发
        if (process.env.NODE_ENV !== 'production') {
            // 数据更新可以在终端看到变化
            mongoose.set('debug', true)
        }

        mongoose.connect(db)

        mongoose.connection.on('disconnect', () => {
            maxConnectTimes++

            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了')
            }
        })

        mongoose.connection.on('error', err => {
            maxConnectTimes++

            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了')
            }
        })

        mongoose.connection.on('open', () => {
            resolve()
            console.log('数据库连接成功')
        })
    })
}